<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px" class="queryForms">
			<el-form-item label="返修任务单" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入返修任务单" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品名称" prop="productName">
				<el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品编号" prop="productNumber">
				<el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="军检状态" prop="militaryInspectionStatus">
				<el-select v-model="queryParams.militaryInspectionStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.army_state" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="请检名称" prop="pleaseCheckName">
				<el-input v-model="queryParams.pleaseCheckName" placeholder="请输入请检名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<CreateForm :ids="ids" formtype="t_armycheck" :special="special" :repairProductId="repairProductId" />
			<right-toolbar @changeTableData="changeTableData" :showSearch.sync="showSearch" @queryTable="handleQuery" menuNames="checkList3" :columns.sync="columns" perm="army:armycheck:index"></right-toolbar>
		</el-row>
		<!--  -->
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<el-table :row-class-name="row_class_name" @mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter" @cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable" ref="table" v-loading="loading" :data="TArmyCheckList" @selection-change="handleSelectionChange" row-key="id" lazy :load="loadListDes" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					           <template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
						           </template
					>
				</el-table-column>

				<el-table-column label="请检名称" prop="pleaseCheckName" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="返修任务单" prop="repairNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="产品代表" prop="productRepresentativeName" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="用户" prop="clientName" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" />
				<!-- <el-table-column label="3B号" prop="bnumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" /> -->
				<!-- <el-table-column label="工艺状态" prop="technologyName" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible" /> -->
				<el-table-column label="军检状态" prop="militaryInspectionStatus" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.army_state" :value="scope.row.militaryInspectionStatus" />
					</template>
				</el-table-column>
				<el-table-column label="备注" prop="remark" min-width="150" :show-overflow-tooltip="true" v-if="columns[8].visible" />

				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)" v-hasPermi="['army:armychecklist:annex']">附件</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['army:armychecklist:delete']">删除</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)" v-hasPermi="['army:armychecklist:annex2']">附件</el-button>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleJump(scope.row)" v-hasPermi="['army:armychecklist:file']">资料</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination5" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<el-dialog title="添加请检计划" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="请检名称" prop="pleaseCheckName">
					<el-input v-model="form.pleaseCheckName" placeholder="请输入请检名称" maxlength="20" show-word-limit />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { armyPlease, listTArmyCheck, listTArmyCheckChild, submitArmyCheck } from "@/api/army/armycheck"
import { armyPleaseList, armyPleaseProduct, deleteProduct } from "@/api/army/checkList"
import CreateForm from "@/views/components/CreateForm"
import { mapGetters } from "vuex"
import { getcolumn } from "@/api/selectList"
export default {
	name: "CheckList",
	components: { CreateForm },
	dicts: ["army_state"],
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			special: true,
			repairProductId: [],
			eleTabTop: 0, //表格容器距浏览器顶部距离
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 军检记录表格数据
			TArmyCheckList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				repairNumber: undefined,
				militaryInspectionStatus: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined,
				pleaseCheckName: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				pleaseCheckName: [{ required: true, message: "请检名称不能为空", trigger: "blur" }]
			},
			testval: undefined,
			// 更新树刷新
			treeMap: new Map(),
			rows: [],
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `请检名称`, visible: true },
				{ key: 1, label: `返修任务单`, visible: true },
				{ key: 2, label: `产品代表`, visible: true },
				{ key: 3, label: `用户`, visible: true },
				{ key: 4, label: `产品名称`, visible: true },
				{ key: 5, label: `产品型号`, visible: true },
				{ key: 6, label: `产品编号`, visible: true },
				{ key: 7, label: `军检状态`, visible: true },
				{ key: 8, label: `备注`, visible: true }
			]
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	created() {
		this.getSize()
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination5" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		handleDelete(row) {
			const ids = row.id
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return deleteProduct(ids)
				})
				.then(() => {
					this.getList()
					this.$refs.table.clearSelection()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => {})
		},
		// 跳转到军检资料
		handleJump(row) {
			// let url = "/army/information?id=" + row.id.replace("c", "")

			let url = `/army/information?id=${row.id.replace("c", "")}&&type=2&&repairProductId=${row.repairProductId}`
			this.$router.push(url)
		},
		/** 提交按钮 */
		submitForm() {
			let data = []
			this.ids.forEach(item => {
				data.push(item.replace("c", ""))
			})
			this.form.ids = data
			this.$refs["form"].validate(valid => {
				if (valid) {
					const loading = this.$loading({
						lock: true,
						text: "Loading",
						spinner: "el-icon-loading",
						background: "rgba(0, 0, 0, 0.7)"
					})
					armyPlease(this.form)
						.then(response => {
							this.$modal.msgSuccess("请检成功")
							this.open = false
							loading.close()
							this.$refs.table.clearSelection()
							this.getList()
						})
						.finally(() => {
							loading.close()
						})
				}
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 查询军检记录列表 */
		getList() {
			this.loading = true
			armyPleaseList(this.queryParams).then(response => {
				this.TArmyCheckList = response.rows
				this.TArmyCheckList.forEach((item, index) => {
					item.hasChildren = true
					item.sort = index + 1
					this.$refs.table.toggleRowExpansion(item, false)
				})
				this.total = response.total
				this.loading = false
			})
		},

		// 获取列表子菜单
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}

			let data = {
				armyPleaseId: tree.id,
				productName: this.queryParams.productName,
				productModel: this.queryParams.productModel,
				productNumber: this.queryParams.productNumber,
				repairNumber: this.queryParams.repairNumber,
				militaryInspectionStatus: this.queryParams.militaryInspectionStatus
			}
			let ret = await armyPleaseProduct(data)
			ret.rows.forEach((item, index) => {
				// 父子id会冲突
				item.id = "c" + item.id
				item.sort = index + 1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.$refs.table.clearSelection()
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				repairId: undefined,
				militaryInspectionNumber: undefined,
				pleaseCheckName: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			// this.currentEnterRow || this.$refs.table.toggleRowSelection(row)
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.repairProductId = selection.map(item => item.repairProductId)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = "添加军检记录"
		},
		handleSubmitChecks() {
			// 判断是否选中了父级返修任务
			let checkp = this.rows.find(item => {
				return Number(item.id) > 0
			})
			if (checkp) {
				this.$modal.msg("只能选择子类产品")
				return false
			}

			this.reset()
			this.open = true
		},
		async handleSubmitCheck() {
			let data = {
				tproductionPlanPaVoList: []
			}
			let formids = []
			// 多条记录
			// this.isOne = false;
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
				// 判断选中的产品列表是否是同一个产品型号
				let modal = undefined
				let checkstatus = false
				let check = this.rows.every(e => {
					if (e.militaryInspectionStatus != "0") {
						checkstatus = true
					}
					let id = e.id.replace("c", "")
					data.tproductionPlanPaVoList.push({
						id: id,
						repairProductId: e.repairProductId,
						productModel: e.productModel,
						productName: e.productName,
						productNumber: e.productNumber,
						repairId: e.repairId
					})
					formids.push(id)
					if (!e.productModel) {
						return false
					} else {
						if (!modal) {
							modal = e.productModel
							return true
						} else {
							return modal == e.productModel
						}
					}
				})
				if (!check) {
					this.$modal.msg("请选择同一型号的产品")
					return false
				}
				if (checkstatus) {
					this.$modal.msg("请选择待核验的产品")
					return false
				}
			}
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					return submitArmyCheck(data)
				})
				.then(() => {
					this.$modal.msgSuccess("操作成功")
					// 刷新树
					this.treeMap.forEach((item, idx) => {
						this.loadListDes({ id: idx }, item.treeNode, item.resolve)
					})
				})
				.catch(() => {})
		},
		// 返修单附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 49,
					perm: "army:armychecklist:annex"
				}
			})
		},
		//  产品附件
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 50,
					perm: "army:armychecklist:annex2"
				}
			})
		}
	}
}
</script>
